package com.example.traffic_learning;

import global.AsyncResponse;
import global.MyArrayList;

import java.util.ArrayList;
import java.util.List;

import DTO.ChapterDTO;
import DTO.SignDTO;
import DTO.TrafficLawDTO;
import DTO.VehicleDTO;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class FragLawTrafficLearning extends Fragment implements AsyncResponse{
	private ArrayList<ChapterDTO> arrChapterDTO = new ArrayList<ChapterDTO>();
	private ArrayList<VehicleDTO> arrVehicleDTO = new ArrayList<VehicleDTO>();
	ArrayList<ArrayList<ArrayList<TrafficLawDTO>>> arrChapter = new ArrayList<ArrayList<ArrayList<TrafficLawDTO>>>();
	private TextView textLaw = null;
	private GetDatabaseTask databaseTask;
	private GetFineDatabaseTask fineDatabaseTask;
	private ConvertText convertText;
	private AsyncResponse asyncResponse = null;
	private ProgressBar progressBar;
	public static String chapter = null;
	private String vehicle;
	private boolean isAll = false;
	private Handler handler = new Handler();
	private SpannableStringBuilder resultSpannedAll = null;
	private MyArrayList<Spanned> listSpanned = new MyArrayList<Spanned>();
	private int index = 0;
	private boolean isLawTrafficLeaning = false;
	private EditText editTextSearch;
	private Spinner spinnerLawType;
	private List<String> list;
	private ArrayAdapter<String> dataAdapter;
	private boolean isFirst = true;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		final View view = inflater.inflate(R.layout.activity_law_traffic_learning, container, false);
		//databaseTask = new GetDatabaseTask(getActivity());
		asyncResponse = this;
		//databaseTask.delegate = asyncResponse;
		textLaw = (TextView)view.findViewById(R.id.text_view_law);
		progressBar = (ProgressBar)view.findViewById(R.id.progress_law_learning);
		progressBar.setVisibility(View.INVISIBLE);
		
		
		spinnerLawType = (Spinner)view.findViewById(R.id.spinner_type_law);
		editTextSearch = (EditText)view.findViewById(R.id.edit_text_search_law);
		
		spinnerLawType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> list, View arg1,
					int pos, long arg3) {
				editTextSearch.setText("");
				if(isLawTrafficLeaning){
					if(list.getItemAtPosition(pos).toString().equals("Tất cả")){
						chapter = arrChapterDTO.get(0).getChapter().toString();
						isAll = true;
						//if(resultSpannedAll == null){
							resultSpannedAll = new SpannableStringBuilder();
							//for(int i = 0; i < arrChapterDTO.size(); i++){
							if(databaseTask != null)
								databaseTask.cancel(true);
				   				databaseTask = new GetDatabaseTask(getActivity());
				   				databaseTask.delegate = asyncResponse;
				   				if(editTextSearch.getText().toString().equals(null)){
				   					databaseTask.execute("");
				   				}else{
				   					databaseTask.execute(editTextSearch.getText().toString());
				   				}
				   					
				   				
				   			//}
						//}
						
					}else{
						//isReload = false;
						chapter = arrChapterDTO.get(pos - 1).getChapter().toString();
						if(databaseTask != null){
			   				//databaseTask.cancel(true);
							if(databaseTask != null)
								databaseTask.cancel(true);
			   				databaseTask = new GetDatabaseTask(getActivity());
			   				databaseTask.delegate = asyncResponse;
			   				if(editTextSearch.getText().toString().equals(null)){
			   					databaseTask.execute("");
			   				}else{
			   					databaseTask.execute(editTextSearch.getText().toString());
			   				}
			   			}
					}
				}else{
					vehicle = arrVehicleDTO.get(pos).getID();
					if(fineDatabaseTask != null){
						fineDatabaseTask.cancel(true);
						fineDatabaseTask = new GetFineDatabaseTask(getActivity());
						fineDatabaseTask.delegate = asyncResponse;
			   			if(editTextSearch.getText().toString().equals(null)){
			   				fineDatabaseTask.execute("", vehicle);
			   			}else{
			   				fineDatabaseTask.execute(editTextSearch.getText().toString(), vehicle);
			   			}
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
					
				
			}
		});
		
		final ImageView imageSearch = (ImageView)view.findViewById(R.id.image_search_law);
		editTextSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				progressBar.setVisibility(View.VISIBLE);
				textLaw.setText("");
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(isLawTrafficLeaning){
					if(editTextSearch.getText().length() == 0){
			   			imageSearch.setVisibility(View.VISIBLE);
			   			if(chapter == null){
			   				Thread thread = new Thread(){
								public void run(){
									handler.post(new Runnable() {
										@Override
										public void run() {
											textLaw.setText(resultSpannedAll);
										}
									});
								}
							};
							thread.start();
		   					progressBar.setVisibility(View.INVISIBLE);
		   				}else{
				   			if(databaseTask != null){	
				   				if(!isFirst){
					   				databaseTask.cancel(true);
					   				databaseTask = new GetDatabaseTask(getActivity());
					   				databaseTask.setFirst(false);
					   				databaseTask.delegate = asyncResponse;
					   				if(chapter == null){
					   					chapter = arrChapterDTO.get(0).getChapter().toString();
										isAll = true;
					   				}
					   				if(editTextSearch.getText().toString().equals(null)){
					   					databaseTask.execute("");
					   				}else{
					   					databaseTask.execute(editTextSearch.getText().toString());
					   				}
				   				}
				   				isFirst = false;
				   			}
		   				}
			   		}else{
			   			if(databaseTask != null){
			   				databaseTask.cancel(true);
			   				databaseTask = new GetDatabaseTask(getActivity());
			   				databaseTask.setFirst(false);
			   				databaseTask.delegate = asyncResponse;
			   				if(editTextSearch.getText().toString().equals(null)){
			   					databaseTask.execute("");
			   				}else{
			   					databaseTask.execute(editTextSearch.getText().toString());
			   				}
			   			}
			   		}
				}else{
					if(fineDatabaseTask != null){
						if(!isFirst){
							fineDatabaseTask.cancel(true);
							fineDatabaseTask = new GetFineDatabaseTask(getActivity());
							fineDatabaseTask.setFirst(false);
							fineDatabaseTask.delegate = asyncResponse;
				   			if(editTextSearch.getText().toString().equals(null)){
				   				fineDatabaseTask.execute("", vehicle);
				   			}else{
				   				fineDatabaseTask.execute(editTextSearch.getText().toString(), vehicle);
				   			}
						}
						isFirst = false;
					}
				}
			}
		});
		showChooseResearch();
		return view;
	}
	
	private String capitalize(String source){
		source = source.toLowerCase();
		String[] words = source.split(" ");
		source = "";
		for(int i = 0; i < words.length; i++){
			if(i < words.length - 1){
				source += Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1) + " ";
			}else{
				source += Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1);
			}
				
		}
		return source;
	}

	@Override
	public void processGetDatabaseFinish(final String output) {
		//if(!isReload){
		if(isAll){
			index++;
			//result += output;
			convertText = new ConvertText(index);
			asyncResponse = this;
			convertText.delegate = asyncResponse;
			convertText.execute(output);
			if(index < arrChapterDTO.size()){	
				
				chapter = arrChapterDTO.get(index).getChapter().toString();
				if(databaseTask != null)
					databaseTask.cancel(true);
				databaseTask = new GetDatabaseTask(getActivity());
   				databaseTask.setFirst(false);
   				databaseTask.delegate = asyncResponse;
				databaseTask.execute("");
				textLaw.setVisibility(View.VISIBLE);
				progressBar.setVisibility(View.INVISIBLE);
			}else{
				index = 0;
				isAll = false;
				chapter = null;
				progressBar.setVisibility(View.INVISIBLE);
			}
		}else{
			databaseTask.cancel(true);
			if(!output.equals("")){
				Thread thread = new Thread(){
					public void run(){
						handler.post(new Runnable() {
							@Override
							public void run() {
								textLaw.setText(Html.fromHtml(output));
							}
						});
					}
				};
				thread.start();
			}else{
				textLaw.setText("Không tìm thấy dữ liệu!");
			}
			
			progressBar.setVisibility(View.INVISIBLE);
			textLaw.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void processConvertTextFinish(final Spanned ouput, int index) {
		//convertText.cancel(true);
		progressBar.setVisibility(View.VISIBLE);
		listSpanned.add(ouput, index);
		if(listSpanned.size() == arrChapterDTO.size()){
			progressBar.setVisibility(View.INVISIBLE);
			for(int i = 0; i < arrChapterDTO.size(); i++){
				try{
					resultSpannedAll.append(listSpanned.getElementByTag(i + 1));
				}catch(Exception e){}
			}
			index = 0;
			Thread thread = new Thread(){
				public void run(){
					getActivity().runOnUiThread(new Runnable() {
		                public void run() {
		                	
		                	if(!ouput.equals("")){
								textLaw.setText(resultSpannedAll);
							}else{
								textLaw.setText("Không tìm thấy dữ liệu!");
							}
		                	databaseTask.cancel(true);
		                	convertText.cancel(true);
		                	listSpanned = new MyArrayList<Spanned>();
		                	chapter = null;
		                }
		            });
				}
			};
			thread.start();
		}
	}
	
	private void showChooseResearch(){
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		final ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
		alertDialogBuilder.setTitle("Chọn nội dung cần tra cứu");
		//final ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
		arrAdapter.add("Luật Giao Thông Đường Bộ");
		arrAdapter.add("Mức Vi Phạm");
		
		alertDialogBuilder.setAdapter(arrAdapter, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which){
				case 0:
					isLawTrafficLeaning = true;	
					arrChapterDTO = ChapterDTO.getAllChapter(getActivity());
					list = new ArrayList<String>();
					list.add("Tất cả");
					for(ChapterDTO chapterDTO : arrChapterDTO){
						list.add(capitalize(chapterDTO.getName()));
					}
					dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.spinner_item, list);
					dataAdapter.setDropDownViewResource(R.layout.spinner_item);
					spinnerLawType.setAdapter(dataAdapter);
					
					isAll = true;
					resultSpannedAll = new SpannableStringBuilder();
					
					chapter = arrChapterDTO.get(0).getChapter().toString();
					databaseTask = new GetDatabaseTask(getActivity());
					break;
				case 1:
					isLawTrafficLeaning = false;
					arrVehicleDTO = VehicleDTO.getAll(getActivity());
					list = new ArrayList<String>();
					for(VehicleDTO vehicleDTO : arrVehicleDTO){
						list.add(capitalize(vehicleDTO.getName()));
					}
					dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.spinner_item, list);
					dataAdapter.setDropDownViewResource(R.layout.spinner_item);
					spinnerLawType.setAdapter(dataAdapter);
					vehicle = arrVehicleDTO.get(0).getID();
					fineDatabaseTask = new GetFineDatabaseTask(getActivity());
					break;
				}
			}
		}).setCancelable(false);
		
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
				getActivity().finish();
				return false;
			}
		});
		alertDialog.show();
	}

	@Override
	public void processGetSignDatabaseFinish(ArrayList<SignDTO> arrayDTO) {
		
	}

	@Override
	public void processGetFineDatabaseFinish(String output) {
		progressBar.setVisibility(View.INVISIBLE);
		textLaw.setText(Html.fromHtml(output));
	}
}
